// pages/booking/detail.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  data: {
    bookingId: null,
    bookingInfo: {},
    loading: true
  },

  onLoad: function(options) {
    // 获取预约ID
    if (options.id) {
      this.setData({
        bookingId: options.id
      });
      
      // 检查登录状态
      const app = getApp();
      if (!app.globalData.isLoggedIn) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 加载预约详情
      this.loadBookingDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow: function() {
    // 检查登录状态是否发生变化
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
  },

  // 返回上一页
  onTapBack: function(e) {
    console.log("onTapBack:",e)
    wx.navigateBack({
      fail:(e)=>{
        console.log("navigateBack:",e)
      },
    });
  },
  
  // 加载预约详情
  loadBookingDetail: function() {
    // 显示加载中
    wx.showLoading({
      title: '加载中...'
    });
    
    // 调用API获取预约详情
    api.order.getBookingDetail(this.data.bookingId)
      .then(res => {
        if (res.success) {
          // 格式化时间
          const bookingInfo = res.data;
          if (bookingInfo.created_at) {
            bookingInfo.created_at = utils.formatTimestampWithTime(bookingInfo.created_at);
          }
          if (bookingInfo.payment_time) {
            bookingInfo.payment_time = utils.formatTimestampWithTime(bookingInfo.payment_time);
          }
          if (bookingInfo.cancel_time) {
            bookingInfo.cancel_time = utils.formatTimestampWithTime(bookingInfo.cancel_time);
          }
          bookingInfo.time = `${utils.formatTimestampWithTime(bookingInfo.start_time)}-${utils.formatTimestampWithTime(bookingInfo.end_time)}`;
          
          // 先设置订单基本信息
          this.setData({
            bookingInfo: bookingInfo,
            loading: false
          });
          // 获取场地详细信息
          if (bookingInfo.venue_id) {
            this.loadVenueDetail(bookingInfo.venue_id);
          }
          
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: '预约详情'
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.message || '获取预约详情失败',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('获取预约详情失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      });
  },
  
  // 加载场地详细信息
  loadVenueDetail: function(venueId) {
    api.venue.getVenueDetail(venueId)
      .then(res => {
        if (res.success) {
          const venueInfo = res.data;
          // 更新场地信息
          this.setData({
            'bookingInfo.store_name': venueInfo.store_name,
            'bookingInfo.store_address': venueInfo.store_address,
            'bookingInfo.store_phone': venueInfo.phone,
            'bookingInfo.venue_name': venueInfo.name,
            'bookingInfo.venue_image': venueInfo.images,
            'bookingInfo.venue_type': venueInfo.venue_type,
            'bookingInfo.venue_price': venueInfo.hour_price,
            'bookingInfo.venue_description': venueInfo.description
          });
        }
      })
      .catch(err => {
        console.error('获取场地详情失败:', err);
      });
  },
  
  // 复制订单号
  copyOrderId: function() {
    const orderId = this.data.bookingInfo.order_no;
    
    if (orderId) {
      wx.setClipboardData({
        data: String(orderId),
        success: () => {
          wx.showToast({
            title: '订单号已复制',
            icon: 'success'
          });
        }
      });
    }
  },
  
  // 开门功能
  onTapOpenDoor: function() {
    wx.showLoading({
      title: '正在开门...'
    });
    
    // 调用开门API
    api.device.openDoor({
      store_id:this.data.bookingInfo.store_id,
      venue_id: parseInt(this.data.bookingInfo.venue_id),
      booking_id: this.data.bookingId
    })
      .then(res => {
        wx.hideLoading();
        
        if (res.success) {
          wx.showToast({
            title: '开门成功',
            icon: 'success'
          });
          // 震动反馈
          wx.vibrateShort();
        } else {
          wx.showToast({
            title: res.message || '开门失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('开门失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      });
  },
  
  // 开电功能
  onTapTurnOnPower: function() {
    wx.showLoading({
      title: '正在开电...'
    });
    
    // 调用开电API
    api.device.openDoor({
      type:1,
      store_id:this.data.bookingInfo.store_id,
      venue_id: parseInt(this.data.bookingInfo.venue_id),
      booking_id: this.data.bookingId
    })
      .then(res => {
        wx.hideLoading();
        
        if (res.success) {
          wx.showToast({
            title: '开电成功',
            icon: 'success'
          });
          // 震动反馈
          wx.vibrateShort();
        } else {
          wx.showToast({
            title: res.message || '开电失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('开电失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      });
  },
  
  // 取消预约
  onTapCancelBooking: function() {
    wx.showModal({
      title: '提示',
      content: '确定要取消该预约吗？',
      success: (res) => {
        if (res.confirm) {
          // 显示加载中
          wx.showLoading({
            title: '取消中...'
          });
          
          // 调用API取消预约
          api.order.cancelBooking(this.data.bookingId)
            .then(res => {
              wx.hideLoading();
              
              if (res.success) {
                wx.showToast({
                  title: '取消成功',
                  icon: 'success'
                });
                
                // 重新加载预约详情
                this.loadBookingDetail();
                
                // 返回上一页并刷新
                setTimeout(() => {
                  const pages = getCurrentPages();
                  const prevPage = pages[pages.length - 2];
                  // 检查prevPage是否存在且有loadBookingList方法
                  if (prevPage && typeof prevPage.resetAndLoadBookingList === 'function') {
                    prevPage.resetAndLoadBookingList();
                  }
                  wx.navigateBack();
                }, 1500);
              } else {
                wx.showToast({
                  title: res.message || '取消失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              wx.hideLoading();
              console.error('取消预约失败:', err);
              wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  
  // 拨打电话
  onTapCallVenue: function() {
    const phone = this.data.bookingInfo.store_phone;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone,
        fail: () => {
          wx.showToast({
            title: '拨打电话失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '暂无联系电话',
        icon: 'none'
      });
    }
  },
  
  // 查看位置
  onTapViewLocation: function() {
    const latitude = this.data.bookingInfo.store_latitude;
    const longitude = this.data.bookingInfo.store_longitude;
    const name = this.data.bookingInfo.store_name;
    const address = this.data.bookingInfo.store_address;

    if (latitude && longitude) {
      wx.openLocation({
        latitude: parseFloat(latitude),
        longitude: parseFloat(longitude),
        name: name,
        address: address,
        scale: 18
      });
    } else {
      wx.showToast({
        title: '暂无位置信息',
        icon: 'none'
      });
    }
  },
  
  // 邀请好友
  onTapInviteFriends: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  
  // 分享给朋友
  onShareAppMessage: function() {
    return {
      title: `我在${this.data.bookingInfo.store_name}的预约`,
      path: `/pages/booking/detail?id=${this.data.bookingId}`,
      imageUrl: this.data.bookingInfo.store_image || '/images/share-default.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在${this.data.bookingInfo.store_name}的预约`,
      query: `id=${this.data.bookingId}`,
      imageUrl: this.data.bookingInfo.store_image || '/images/share-default.png'
    };
  }
});